package packet

import "fmt"

type PacketReader interface {
	ReadBytes(len uint16) []byte
	ReadByte() byte
	ReadShort() int16
	ReadUShort() uint16
	ReadInt() int32
	ReadUInt() uint32
	ReadLong() int64
	ReadULong() uint64
	ReadAsciiString(len uint16) string
	ReadMapleAsciiString() string
	Available() uint16
}

func (r *maplePacketReader) ReadBytes(len uint16) []byte {
	b := []byte(r.maplePacket[r.pos : r.pos+len])
	r.pos += len
	return b
}

func (r *maplePacketReader) ReadByte() byte {
	b := byte(r.maplePacket[r.pos])
	r.pos++
	return b
}

func (r *maplePacketReader) ReadShort() int16 {
	return int16(r.ReadByte()) | (int16(r.ReadByte()) << 8)
}

func (r *maplePacketReader) ReadUShort() uint16 {
	return uint16(r.ReadByte()) | (uint16(r.ReadByte()) << 8)
}

func (r *maplePacketReader) ReadInt() int32 {
	var result = int32(0)
	for i := 0; i < 4; i++ {
		shift := byte(i * 8)
		result += int32(r.ReadByte() << shift)
	}
	return result
}

func (r *maplePacketReader) ReadUInt() uint32 {
	var result = uint32(0)
	for i := 0; i < 4; i++ {
		shift := byte(i * 8)
		result += uint32(r.ReadByte() << shift)
	}
	return result
}

func (r *maplePacketReader) ReadLong() int64 {
	var result = int64(0)
	for i := 0; i < 8; i++ {
		shift := byte(i * 8)
		a := (int64(r.ReadByte() << shift))
		fmt.Println(a)
		result += a
	}
	return result
}

func (r *maplePacketReader) ReadULong() uint64 {
	var result = uint64(0)
	for i := 0; i < 4; i++ {
		shift := byte(i * 8)
		result += uint64(r.ReadByte() << shift)
	}
	return result
}

func (r *maplePacketReader) ReadAsciiString(len uint16) string {
	data := r.ReadBytes(len)
	return string(data)
}

func (r *maplePacketReader) ReadMapleAsciiString() string {
	return r.ReadAsciiString(r.ReadUShort())
}

func (r *maplePacketReader) Available() uint16 {
	return r.maplePacket.Size() - r.pos
}
